#include "xict_ui_common/utils/net_tool.h"
#include <QProcess>
#include <QTextCodec>

namespace xict_ui_common {

    bool NetTool::checkPing(const QString& host) {
        std::vector<std::string> v;
        std::array<char, 128> buffer;
        QString cmd = "ping " + host + " -c 2 -w 2";
        std::unique_ptr<FILE, decltype(&pclose)> pipe(
            popen(cmd.toStdString().c_str(), "r"), pclose);
        if (!pipe) {
            throw std::runtime_error("popen() failed!");
            return false;
        }
        while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {
            v.push_back(buffer.data());
        }

        // 读取倒数第二行 2 packets transmitted, 2 received, 0% packet loss,
        // time 1001ms
        if (v.size() > 1) {
            std::string data = v[v.size() - 2];
            int iPos         = data.find("已接收 ");
            if (iPos != -1) {
                data = data.substr(iPos + 10, 3);   // 截取字符串返回packet loss
                int n = atoi(data.c_str());
                if (n == 2)
                    return true;
                else
                    return false;
            }

            int jPos = data.find("received,");
            if (jPos != -1) {
                data = data.substr(jPos + 10, 3);   // 截取字符串返回packet loss
                int n = atoi(data.c_str());
                if (n == 0)
                    return true;
                else
                    return false;
            }
        }
        return false;
    }

    QString NetTool::getPingTime(const QString& host) {
        QProcess exc;
        QTextCodec* codec = QTextCodec::codecForName("GBK");
        QString cmdstr    = "ping " + host + " -c 2 -w 2";
        exc.start(cmdstr);                                  //执行ping
        exc.waitForFinished(-1);                            //等待ping完成
        QString outstr = codec->toUnicode(exc.readAll());   //获取ping结果
        //返回不等于-1，说明ping结果包含"往返行程的估计时间"字段，则说明ping成功，网络可达;等于-1，表示没有此字段，说明ping不通
        QString test       = "ms";
        int flag           = outstr.indexOf(test);
        QString time_total = "0";
        QString time       = "0";
        if ((-1 != flag)) {
            int start_num = flag - 1;
            while (true) {
                if (outstr.mid(start_num - 1, 1) == "<" ||
                    outstr.mid(start_num - 1, 1) == "=") {
                    break;
                }
                start_num--;
            }
            time_total        = outstr.mid(start_num, flag - start_num);
            QStringList parts = time_total.split("/");
            time              = parts.at(1);
        }
        return time;
    }

}   // namespace xict_ui_common
